const {userModel, userDetailModel} = require("../models/user");
const jwt = require("jsonwebtoken");
const jwtconfig = require("../config/jwtConfig");

const userAdd = async (ctx) => {
  let { username, password } = ctx.request.body;
  const res = await userModel.findOne({ username });
  if (res) {
    ctx.body = { code: 407, msg: "此用户已存在" };
  } else {
    await userModel
      .create({ username, password })
      .then((result) => {
        ctx.body = { code: 200, data: null, msg: "添加用户成功" };
      })
      .catch((err) => {
        ctx.body = { code: 400, msg: "新增用户异常" };
      });
  }
};
const userLogin = async (ctx) => {
  let { username, password, grant_type } = ctx.request.body;
  if (!grant_type || grant_type !== "password") {
    ctx.body = { code: 400, msg: "非法请求" };
    return;
  }
  const res = await userModel.findOne({ username, password });
  if (res) {
    const data = {
      OrgId: res.OrgId,
      UserId: res.UserId
    }
    const token = jwt.sign(
      data,
      jwtconfig.Key,
      {
        expiresIn: '7d' //单位是 秒
      }
    );
    ctx.body = {
      code: 200,
      msg: "获取用户成功",
      data: {
        token
      },
    };
  } else {
    ctx.body = { code: 404, msg: "未查询到用户信息", data: null };
  }
};
const userGetDetailsById = async (ctx) => {
  const { UserId } = ctx.request.query;
  const res = await userDetailModel.findOne({ UserId });
  if (res) {
    ctx.body = {
      code: 200,
      msg: "获取用户成功",
      data: res,
    };
  } else {
    ctx.body = {
      code: 404,
      msg: "未查询到该用户信息",
      data: null,
    };
  }
}
module.exports = {
  userAdd,
  userLogin,
  userGetDetailsById
};
